<template>
  <section class="content">
    <Panel :expandable="false" :expanded="true" color="#67C23A">
      <template slot="title">报关单查询</template>
      <template slot="body">
        <input @change="fileupdate($event)" ref="orderFile" type="file" style="display: none" id="orderFile" accept="application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet">
        <el-form class="search-form">
          <el-row>
            <el-col :span="10">
              <el-form-item label="报关单号:" :label-width="labelWidth">
                <el-input :disabled="param.isImported===0" v-model="param.declareNo" placeholder="请输入您要查询的报关单号" style="width:400px"></el-input>
              </el-form-item>
              <el-form-item label="导入日期:" :label-width="labelWidth">
                <el-date-picker
                  v-model="dateRange"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  class="full-cell"
                  type="datetimerange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  :disabled="param.isImported===0"
                  style="width: 400px !important;">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12" :offset="1">
              <el-form-item label="订单编号:" label-width="119px">
                <el-input v-model="param.orderId" placeholder="请输入您要查询的订单编号"  style="width:400px"></el-input>
              </el-form-item>
              <el-form-item label="已导入报关单:" label-width="119px">
                <el-radio v-model="param.isImported" :label="1">是</el-radio>
                <el-radio v-model="param.isImported" :label="0">否</el-radio>

                <el-button type="success" style="margin-left: 80px" @click="handleSearch">搜索</el-button>
                <el-dropdown trigger="click" split-button type="primary" style="margin-left: 20px" @command="handleClick">
                  报关单导入
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item command="1">报关单导入</el-dropdown-item>
                    <el-dropdown-item command="2">报关单导入模板下载</el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </template>
    </Panel>

    <Panel :expandable="false" :expanded="true" :hasTitle="false">
      <template slot="body">
        <el-table :data="list" header-row-class-name="header-class">
            <el-table-column type="index" label="序号" width="60">

            </el-table-column>
            <el-table-column prop="declareNo" label="报关单号" align="center">
                
            </el-table-column>
            <el-table-column prop="createTime" label="导入时间" align="center">
                
            </el-table-column>
            <el-table-column prop="orderId" label="订单号" align="center">
                
            </el-table-column>
            
            <el-table-column prop="orderCreated" label="订单时间" align="center">
                
            </el-table-column>
        </el-table>
        <div class="clear-fix">
          <el-pagination
              style="float: right; margin-top: 20px;"
              background
              layout="total,prev, pager, next"
              :total="searchParam.total"
              :pager-count="6"
              :current-page.sync="searchParam.page"
               @current-change="handleCurrentChange"
              >
          </el-pagination>
        </div>
      </template>
    </Panel>

    <el-dialog class="error-dialog" width="700px" title="失败" :visible.sync="errorDialogVisible">
      <div style="margin-bottom: 31px">以下订单对应报关单未导入，请检查<el-button type="primary" style="float: right" @click="handleExportError">导出报关单信息</el-button></div>
      <el-table id="errorTable" :data="errorList" header-row-class-name="header-class">
        <el-table-column prop="orderId" align="center" label="订单编号"></el-table-column>
        <el-table-column prop="message" align="center" label="失败原因"></el-table-column>
      </el-table>
      <div class="clear-fix">
        <el-pagination
          style="float: right; margin-top: 20px;"
          background
          layout="total,prev, pager, next"
          :total="errorTotal"
          :pager-count="6"
          @current-change="handleErrorCurrentChange"
        />
      </div>
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button @click="errorDialogVisible = false">关闭</el-button>
      </div>
      <a style="display: none" id="download"></a>
    </el-dialog>

    <el-dialog :class="isSuccessful?'success-dialog' : 'error-dialog'" width="340px" :title="isSuccessful? '成功' : '失败'" :visible.sync="errorDialogVisible2">
      {{isSuccessful? '本次导入订单成功！' : errorMsg}}
    </el-dialog>
  </section>
</template>

<script>
  // import pagination from '@/components/common/pageComponent'
  import instance from '@/api/index.js'
  import baseURL from '@/js/common/baseURL'
  import axios from 'axios'
  import Panel from '@/components/common/panel'
  import XLSX from 'xlsx'
  import ClientPagination from '@/js/common/ClientPagination'

  export default {
    name: "customsDeclaration",
    data() {
      return {
        labelWidth: '90px',
        errorDialogVisible: false,
        errorDialogVisible2: false,
        errorMsg: "上传文件格式错误，请检查文件格式是否正确！",
        isSuccessful: false,
        errorList: [],
        errorTotal: 0,
        errorPage: 1,
        file: '',//上传的文件
        param: {
          beginDate: '', //开始日期
          endDate: '', //结束日期
          orderId: '', //订单id
          declareNo: '', //报关单号
          isImported: 1
        },
        searchParam: {
          page: 1,
          rows: 10,
          total: 0
        },
        dateRange: [],
        allList: [],
        list: [],
        clientPagination: null
      }
    },
    methods: {
      handleSearch() {
        this.searchParam.page = 1;
        this.getDeclareList();
      },
      //报关单列表获取
      getDeclareList: function () {
        let vm = this;
        let param = {
          orderId: this.param.orderId,
          declareNo: this.param.declareNo,
          isImported: this.param.isImported,
          page: this.searchParam.page,
          rows: this.searchParam.rows
        };
        if(this.dateRange) {
          param.beginDate = this.dateRange[0];
          param.endDate = this.dateRange[1];
        }
        if(param.isImported === 0) {
          delete param.declareNo;
          delete param.beginDate;
          delete param.endDate;
        }
        
        instance({
          method: 'post',
          url: '/v1/declare/query',
          data: param
        }).then(function (data) {
          vm.list = data.data.data.list;
          // vm.searchParam.page = 1;
          vm.searchParam.total = data.data.data.total;
        });
      },
      //报关单模板下载
      handleDownloadTemplate() {
        let url = baseURL+'/v1/declare/download';
        let link = document.createElement('a');
        link.style.display = 'none';
        link.href = url;
        link.setAttribute('download', '报关单模板');
        document.body.appendChild(link);
        link.click();
      },

      //文件选择
      orderFileClick: function () {
        document.getElementById('orderFile').click();
      },
      fileupdate: function (event) {
        let vm = this;
        vm.file = event.target.files[0];
        let formData = new FormData();
        formData.append("fileName", vm.file);
        // loading
        this.loading = this.$loading({
            lock: true,
            // text: 'Loading',
            // spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
        });
        axios({
          url: baseURL + '/v1/declare/import',
          method: 'post',
          data: formData,
        }).then(function (data) {
          if(vm.loading) {
              vm.loading.close();
          }
          if(data.data.success){
            if(data.data.data && data.data.data.length) {
              vm.isSuccessful = false;
              vm.errorDialogVisible = true;
              // vm.errorList = data.data.data;
              vm.clientPagination.data = data.data.data;
              vm.clientPagination.handleCurrentChange(1);
              vm.errorList = vm.clientPagination.subList;
              vm.errorPage = 1;
              vm.errorTotal = vm.clientPagination.searchParam.total;
            } else if(data.data.msg) {
              vm.isSuccessful = false;
              vm.errorMsg = data.data.msg;
              vm.errorDialogVisible2 = true;
            } else {
              vm.isSuccessful = true;
              vm.errorDialogVisible2 = true;
              vm.getDeclareList();
            }
          }else {
            debugger;
            vm.errorDialogVisible2 = true;
            vm.isSuccessful = false;
            vm.errorMsg = data.data.msg || "上传失败！";
          }
          vm.$refs.orderFile.value = '';
        }).catch(function (err) {
          if(vm.loading) {
              vm.loading.close();
          }
          console.log(err);
          vm.errorDialogVisible2 = true;
          vm.isSuccessful = false;
          vm.errorMsg = "上传失败！";
          vm.$refs.orderFile.value = '';
        })
      },


      handleClick(command) {
        if(command == '1') {
          this.orderFileClick();
        } else {
          this.handleDownloadTemplate();
        }
      },

      handleExportError() {
        let ws_data = [
          [ "订单编号", "失败原因"]
        ];

        if(this.clientPagination && this.clientPagination.data && this.clientPagination.data.length) {
          this.clientPagination.data.forEach((d)=>{
            ws_data.push([d.orderId, d.message]);
          });
        }

        let ws = XLSX.utils.aoa_to_sheet(ws_data);
        /* create a new blank workbook */
        var wb = XLSX.utils.book_new();
        /* Add the worksheet to the workbook */
        XLSX.utils.book_append_sheet(wb, ws, "sheet1");
        XLSX.writeFile(wb, "sheetjs.xlsx");
      },

      handleCurrentChange(page) {
        this.searchParam.page = page;
        this.getDeclareList();
      },
      handleErrorCurrentChange(page) {
        this.errorPage = page;
        this.clientPagination.handleCurrentChange(page);
        this.errorList = this.clientPagination.subList;
        this.errorTotal = this.clientPagination.searchParam.total;
      }
    },
    created() {
      this.getDeclareList();
      this.clientPagination = new ClientPagination();
      this.clientPagination.search(function(){return true;});
    },
    components: {
      Panel
    }
  }
</script>

<style>
.search-form .el-form-item__label{
  font-weight: 400;
}

.search-form .el-form-item {
  margin-bottom: 16px;
}

.search-form .el-range-input {
  text-align: left;
}

.error-dialog .el-dialog__header {
  border-bottom: 1px solid #E4E7ED;
}

.error-dialog .el-dialog__header .el-dialog__title {
  color: #FF9328;
}

.success-dialog .el-dialog__header {
  border-bottom: 1px solid #E4E7ED;
}

.success-dialog .el-dialog__header .el-dialog__title {
  color: #69C33D;
}
</style>
